import { rpx2px } from '../../utils/utils.js'
import { hsv2rgb, rgb2hsv, rgb2hex } from './utils'

// 取色块大小
const blockSize = rpx2px(10);
// 饱和值区域: hsv.s hsv.v
let SV;

Component({
  properties: {
    initColor: {
      type: String,
      value: 'rgb(255,255,255)'
    },
    show: {
      type: Boolean,
      value: false
    },
    left: {
      type: Number,
      value: 0
    }
  },
  data: {
    hueColor: 'rgb(255, 0, 0)', // 色相 用 rgb 表示
    hexColor: '#FFFFFF', // hex 表示
    hsvColor: {
      h: '0',
      s: '0',
      v: '100'
    },
    rgbColor: 'rgb(255,255,255)',
    x: 0,
    y: 0
  },
  lifetimes: {
    attached() {
      let { initColor } = this.data;
      this.setData({
        hueColor: hsv2rgb((rgb2hsv(initColor)).h, 100, 100), // 色相
        hexColor: rgb2hex(initColor),
        hsvColor: rgb2hsv(initColor),
      })
    },
    ready() {
      const $ = this.createSelectorQuery()
      const target = $.select('.picker-sv')
      target.boundingClientRect()
      $.exec((res) => {
        const rect = res[0]
        if (rect) {
          SV = {
            W: rect.width - blockSize,
            H: rect.height - blockSize,
            StepX: (rect.width - blockSize) / 100,
            StepY: (rect.height - blockSize) / 100
          }
          let { s, v } = this.data.hsvColor;
          // 初始化定位
          this.setData({
            x: Math.round(s * SV.StepX),
            y: Math.round((100 - v) * SV.StepY)
          })
        }
      })
    }
  },
  methods: {
    onEnd() {
      this.triggerEvent('change', {
        color: this.data.rgbColor
      })
    },
    onClose() {
      this.triggerEvent('close');
    },
    // 修改色相
    changeHue: function (e) {
      let hue = e.detail.value;
      let rgbColor = hsv2rgb(hue, this.data.hsvColor.s, this.data.hsvColor.v);
      this.setData({
        "hsvColor.h": hue,
        hueColor: hsv2rgb(hue, 100, 100),
        rgbColor,
        hexColor: rgb2hex(rgbColor)
      })
    },
    // 修改饱和值
    changeSV: function (e) {
      let {
        x,
        y
      } = e.detail;
      x = Math.round(x / SV.StepX);
      y = 100 - Math.round(y / SV.StepY);
      let rgbColor = hsv2rgb(this.data.hsvColor.h, x, y);
      this.setData({
        "hsvColor.s": x,
        "hsvColor.v": y,
        rgbColor,
        hexColor: rgb2hex(rgbColor)
      })
    }
  }
})
